﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Users;

namespace RBAC.Api.Writh.CommandHandler.Users
{
    public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<User> user;
        private readonly IMapper mapper;
        private readonly IBaseRepositry<UserRole> userole;

        public UpdateUserCommandHandler(IBaseRepositry<User> baseRepositry,
                            IMapper mapper,
                            IBaseRepositry<UserRole> baseRepositry1)
        {
            this.user = baseRepositry;
            this.mapper = mapper;
            this.userole = baseRepositry1;
        }
        public async Task<APIResult<object>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "修改用户成功";

            var strategy = user.Context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            { 
                using (var tran = await user.Context.Database.BeginTransactionAsync())
                { 
                    try
                    { 
                        //修改用户
                        var users = mapper.Map<User>(request);
                        await user.Update(users);

                        //先删除用户角色
                        var ur=userole.GetAll().Where(x=>x.UserId== users.Id).ToList();
                        foreach(var item in ur)
                        {
                            await userole.Delete(item);
                        }
                        //添加用户角色
                        foreach (var item in request.RoleId)
                        {
                            UserRole useroles = new()
                            {
                                UserId= users.Id,
                                RoleId=item,
                                CreateTime=DateTime.Now,
                                State=request.State
                            };
                            await userole.Add(useroles);
                        }
                        await tran.CommitAsync();

                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync();
                        result.Code = ResultCode.Fail;
                        result.Message = "修改用户失败";
                    }
                }
            });


            return await Task.FromResult(result);
        }
    }
}
